import React from 'react';
import styled from 'styled-components'

const Wrapper = styled.div`
  width: 100%;
  padding: 3rem;

  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(3, 1fr);
  place-items: center;
`
const PlaceHolder = styled.div`
  border: .7rem dashed hsl(192, 100%, 50%);
  padding: .7rem;
  &.highlight {
    background-color: rgba(255,255,255, .7);
    border: .7rem dashed hsl(32, 100%, 50%);
  }
`
const ItemContainer = styled.div`
  border: .3rem dotted hsl(128, 100%, 50%);
  padding: .1rem;
  width: 7rem;
  height: 7rem;
  line-height: 7rem;
`
const Card = styled.div`
  font-size: 4rem;
  background-color: hsl(168, 80%, 80%);
  color: hsl(30, 90%, 50%);
  font-weight: bold;

  &.current {
    color: white;
  }
`

const INIT_ITEMS = [
  '🐳',  '🍄',  '',   '🥝', 
  '',    '❄️',  '🦔', '',
  '🥇',  '',    '🚀', '',
]
export default function Demo() {
  const [items, setItems] = React.useState(INIT_ITEMS)
  const [source, setSource] = React.useState<null | number>(null)
  const [target, setTarget] = React.useState<null | number>(null)
  const refFileInput = React.useRef<any>()

  const onDragStart = (id:number) => (e:any) => {
    // console.log(`#${id} - `, e)
    if (source !== id) setSource(id)
  }
  const onDragOver = (id:number) => (e:any) => {
    // console.log(`#${id} - `, e)
    e.preventDefault();
    if (target !== id) setTarget(id)
  }
  const onDragLeave = (id:number) => (e:any) => {
    // console.log(`#${id} - `, e)
    setTarget(null)
  }
  const onDrop = (id:number) => (e:any) =>{
    console.log(`#${id} - `, e)
    setSource(null)
    setTarget(null)
    if ((target !== null) && (source !== null)) {
      items[target] = items[source]
      items[source] = ''
      setItems([ ...items ])
    }
  }
  const onDropFile = (e:any) => {
    console.log('files', e.dataTransfer.files)
    e.preventDefault();
    refFileInput.current.files = e.dataTransfer.files;
  }
  return (
    <div>
    <div>
      <input type="file" ref={refFileInput} />
    </div>
    <Wrapper>
      
    { items.map((x:string, index:number) => (
      <PlaceHolder key={index} 
        className={(index===target) ? 'highlight' : ''} 
        onDragOver={!x ? onDragOver(index) : undefined}
        onDragLeave={onDragLeave(index)}
        onDrop={onDropFile}
      >
        <ItemContainer draggable={!!x} 
          onDragStart={onDragStart(index)}
          onDrop={onDrop(index)}
        >
          <Card className={(source === index) ? "current" : ""}>{x}</Card>
        </ItemContainer>
      </PlaceHolder>

    )) }
    </Wrapper>
    </div>
  );
}
